package com.example.gsq.news.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.gsq.news.R;
import com.example.gsq.news.base.BaseActivity;
import com.example.gsq.news.base.BaseFragment;
import com.example.gsq.news.bean.News;
import com.example.gsq.news.ui.activity.MainActivity;
import com.example.gsq.news.util.C;

import java.util.List;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;

public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public static final int VIEW_TYPE_ITEM = 0;
    public static final int VIEW_TYPE_FOOTER = 1;
    private Context mContext;
    private BaseFragment mFragment;
    private List<News> mNewsList;
    private OnItemClickListener mItemClickListener;
    private RecyclerView mRecyclerView;
    private RelativeLayout mFooterLayout;
    private OnLoadMoreListener mLoadMoreListener;
    private LruCache<String, Bitmap> mImageCache;
    private int mFirstVisibleItem;
    private int mLastVisibleItem;

    public NewsAdapter(Context context, List<News> newsList) {
        mContext = context;
        mNewsList = newsList;
        int size = (int) (Runtime.getRuntime().maxMemory() / 4);
        mImageCache = new LruCache<>(size);
    }

    public NewsAdapter(BaseFragment fragment, List<News> newsList) {
        mFragment = fragment;
        mNewsList = newsList;
        int size = (int) (Runtime.getRuntime().maxMemory() / 4);
        mImageCache = new LruCache<>(size);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == VIEW_TYPE_ITEM) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_news_item, parent, false);
        } else if (viewType == VIEW_TYPE_FOOTER) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_news_footer, parent, false);
            mFooterLayout = (RelativeLayout) view;
        }
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == VIEW_TYPE_ITEM) {
            News news = mNewsList.get(position);
            String itemImageUrl = news.getItemImageUrl();
            ((ItemViewHolder) holder).itemImage.setTag(itemImageUrl);
            if (mImageCache.get(itemImageUrl) == null) {
                ((ItemViewHolder) holder).itemImage.setImageResource(R.mipmap.image_loading);
            } else {
                ((ItemViewHolder) holder).itemImage.setImageBitmap(mImageCache.get(itemImageUrl));
            }
            ((ItemViewHolder) holder).itemTitle.setText(news.getTitle());
//            ((ItemViewHolder) holder).itemDesc.setText(news.getContentUrl());
            ((ItemViewHolder) holder).itemDate.setText(news.getDate());
        } else if (getItemViewType(position) == VIEW_TYPE_FOOTER) {
        }
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.mLoadMoreListener = onLoadMoreListener;
    }

    public interface OnLoadMoreListener {
        void startLoadMore();
    }

    public void loadImageWhenStopScroll() {
        for (int i = mFirstVisibleItem; i <= mLastVisibleItem && i != getItemCount() - 1; i++) {
            String imageUrl = mNewsList.get(i).getItemImageUrl();
            if (mImageCache.get(imageUrl) == null) {
                if (mContext != null) {
                    ((BaseActivity) mContext).doAsyncTask(C.TaskId.ACTIVITY_GET_ITEM_BITMAP, imageUrl);
                } else if (mFragment != null) {
                    mFragment.doAsyncTask(C.TaskId.FRAGMENT_GET_ITEM_BITMAP, imageUrl);
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return mNewsList.size() + 1;
    }

    class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView itemImage;
        TextView itemTitle;
        TextView itemDesc;
        TextView itemDate;
        ItemViewHolder(View itemView) {
            super(itemView);
            itemImage = (ImageView) itemView.findViewById(R.id.item_image);
            itemTitle = (TextView) itemView.findViewById(R.id.item_title);
            itemDesc = (TextView) itemView.findViewById(R.id.item_desc);
            itemDate = (TextView) itemView.findViewById(R.id.item_date);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            mItemClickListener.onItemClick(v, getAdapterPosition());
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        mRecyclerView = recyclerView;
//        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
//            @Override
//            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//                return makeMovementFlags(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.RIGHT);
//            }
//
//            @Override
//            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//                return false;
//            }
//
//            @Override
//            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//                int position = viewHolder.getAdapterPosition();
//                mNewsList.remove(position);
//                notifyItemRemoved(position);
//                loadImageWhenStopScroll();
//            }
//        });
//        itemTouchHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE) {
                    loadImageWhenStopScroll();
// if (getItemCount() > 0 && mFooterLayout.getVisibility() == View.VISIBLE) {
                    if (mLastVisibleItem == mNewsList.size()) {
                        mLoadMoreListener.startLoadMore();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                mFirstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                mLastVisibleItem = layoutManager.findLastVisibleItemPosition();
                if (mFirstVisibleItem == 0 && mImageCache.get(mNewsList.get(0).getItemImageUrl()) == null) {
                    loadImageWhenStopScroll();
                }
            }
        });
    }

//    public void setFooterStatus(int status) {
//        mFooterLayout.setVisibility(status);
//    }

    @Override
    public int getItemViewType(int position) {
        if (position == getItemCount() - 1) {
            return VIEW_TYPE_FOOTER;
        }
        return VIEW_TYPE_ITEM;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public LruCache<String, Bitmap> getLruCache() {
        return mImageCache;
    }
}